package edu.pku.sei.transformation.editor.controller.commands.link;

import org.eclipse.gef.commands.CompoundCommand;

import edu.pku.sei.modeler.model.structure.MetaDiagram;
import edu.pku.sei.modeler.model.structure.MetaLink;
import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.transformation.editor.controller.commands.CommandFactory;
import edu.pku.sei.transformation.editor.model.Transformation;
import edu.pku.sei.transformation.editor.model.TransformationFormalParameter;
import edu.pku.sei.transformation.editor.model.TypedModel;

public class TransformationFormalParameterDeleteCommand extends AbstractLinkDeleteCommand<TransformationFormalParameter, Transformation, TypedModel> {
	private MetaDiagram diagram;
	private MetaNode referenceNode;
	private CompoundCommand linkCommands = new CompoundCommand();
	
	public TransformationFormalParameterDeleteCommand(
			TransformationFormalParameter link,
			Transformation source, TypedModel target) {
		super(link, source, target);
		diagram = source.getDiagram();
		if (diagram != null) {
			for (Object node : diagram.getNodes()) {
				if (node instanceof MetaNode && ((MetaNode)node).getModelElement() == target) {
					referenceNode = (MetaNode) node;
					break;
				}
			}
			if (referenceNode != null) {
				for (Object refNodeLink : referenceNode.getIncomings()) {
					linkCommands.add(CommandFactory.getDeleteCommand((MetaLink)refNodeLink));
				}
				for (Object refNodeLink : referenceNode.getOutgoings()) {
					linkCommands.add(CommandFactory.getDeleteCommand((MetaLink)refNodeLink));
				}
			}
		}
		
	}

	@Override
	public void execute() {
		source.getModelParameter().remove(link);
		link.setTypedModel(null);
		if (diagram != null && referenceNode != null)
			diagram.getNodes().remove(referenceNode);
		linkCommands.execute();
	}
	
	@Override
	public void undo() {
		source.getModelParameter().add(link);
		link.setTypedModel(target);
		if (diagram != null && referenceNode != null)
			diagram.getNodes().add(referenceNode);
		linkCommands.undo();
	}
}
